package com.wanghua.spring.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/*
* Filter 与 Listener 都属于 Servlet 的规范。
* 字符编码 Filter。
* 字符编码常用来解决 Tomcat 等服务器里 request、response 乱码的问题。在将请求提交到 Servlet 之前对 request 进行编码。
* 页面编码方式必须与 Filter 编码方式一致。另外，如果表单是 GET 方式提交的，还需要修改 Tomcat 的 /config/server.xml 配置文件，
* 指定 URIEncoding（默认为 ISO-8859-1）；否则仍然会乱码。修改如下：
  <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />
* */
public class CharacterEncodingFilter implements Filter {
    private String characterEncoding;
    private boolean enabled;

    @Override
    public void init(FilterConfig config) throws ServletException {
        characterEncoding = config.getInitParameter("characterEncoding");  //配置在 web.xml
        enabled = "true".equalsIgnoreCase(config.getInitParameter("enabled").trim());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain chain) throws IOException, ServletException {
        if (enabled || characterEncoding != null) {
            servletRequest.setCharacterEncoding(characterEncoding);
            servletResponse.setCharacterEncoding(characterEncoding);
        }
        chain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        characterEncoding = null;
    }
}